package kr.hkit.androidcomplete03.ch25;

import kr.hkit.androidcomplete03.R;
import android.R.integer;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class SQLiteTest extends Activity {

	WordDbHelper mHelper;
	ListView list;
	WordDAO dao;
	SimpleCursorAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch25_sqlitetest);
		mHelper = new WordDbHelper(this);
		list = (ListView) findViewById(R.id.ch25_sqllitetest_list);
		dao = WordDAO.open(this);
	}
	
	public void mOnClick(View v){
		boolean result;
		String str = null;
		
		switch (v.getId()) {
		case R.id.ch25_sqllitetest_insertBtn:
			EditText eng = (EditText) findViewById(R.id.ch25_sqllitetest_engEdit);
			EditText han = (EditText) findViewById(R.id.ch25_sqllitetest_hanEdit);
			
			result = dao.insert(eng.getText().toString(), han.getText().toString());
			str = result?"Insert Success" : "Insert Fail";
			
			eng.setText("");
			han.setText("");
			break;

		case R.id.ch25_sqllitetest_deleteAllBtn:
			result = dao.deleteAll();
			str = result? "Delete All Success": "Delete All Fail";
			break;
			
		case R.id.ch25_sqllitetest_deleteBtn:
			EditText num = (EditText) findViewById(R.id.ch25_sqllitetest_idEdit);
			int idx = Integer.parseInt(num.getText().toString());
			result = dao.delete(idx);
			str = result? "Delete Success" : "Delete Fail";
			num.setText("");
			break;
			
		case R.id.ch25_sqllitetest_selectBtn:
			Cursor cursor = dao.selectAll();
			startManagingCursor(cursor);
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
					R.layout.ch25_sqllite_listrow, 
					cursor, 
					new String[]{"_id","eng","han"}, 
					new int[] {R.id.ch25_sqllite_listnum, R.id.ch25_sqllite_listeng, R.id.ch25_sqllite_listhan} );
			list.setAdapter(adapter);
			str = "Select All Success";
			
			break;
			
		case R.id.ch25_sqllitetest_updatebtn:
			EditText updateNum = (EditText) findViewById(R.id.ch25_sqllitetest_updatenum);
			EditText updateEng = (EditText) findViewById(R.id.ch25_sqllitetest_updateeng);
			EditText updateHan = (EditText) findViewById(R.id.ch25_sqllitetest_updatehan);
			int id = Integer.parseInt(updateNum.getText().toString());
			
			result = dao.update(id, updateEng.getText().toString(), updateHan.getText().toString());
			str = result? "Update Success" : "Update Fail";
			updateNum.setText("");
			updateEng.setText("");
			updateHan.setText("");
			break;
		}
		
		Toast.makeText(this, str, Toast.LENGTH_LONG).show();
		
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		dao.close();
	}
}
